﻿using System;
using Microsoft.DirectX.DirectInput;

namespace breakoutsharp
{
    public class DxKeyboard : IDisposable
    {
        private Device device = null;
        private bool disposed = false;

        public DxKeyboard(System.Windows.Forms.Form form)
        {
            device = new Device(SystemGuid.Keyboard);
            device.SetCooperativeLevel(form, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
            device.SetDataFormat(DeviceDataFormat.Keyboard);

            try
            {
                device.Acquire();
            }
            catch (Microsoft.DirectX.DirectXException)
            {
                throw;
            }
        }

        public KeyboardState State
        {
            get
            {
                return device.GetCurrentKeyboardState();
            }
        }

        public Key[] PressedKeys
        {
            get
            {
                return device.GetPressedKeys();
            }
        }

        public void Poll()
        {
            try
            {
                device.Poll();
                
                
            }
            catch (NotAcquiredException)
            {
                try
                {
                    device.Acquire();
                }
                catch (Exception)
                {
                    
                    throw;
                }
                throw;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (!(device == null))
                    {
                        device.Unacquire();
                    }

                }
                disposed = true;
            }
        }

        #endregion
    }
}
